package com.etl.dataflow.scheduler.admin.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etl.dataflow.common.entity.ExecutorInfo;
import com.etl.dataflow.common.enums.TaskStateEnum;
import com.etl.dataflow.common.response.Code;
import com.etl.dataflow.common.response.R;
import com.etl.dataflow.scheduler.admin.entity.DataflowTaskInfo;
import com.etl.dataflow.scheduler.admin.entity.DataflowTaskRecord;
import com.etl.dataflow.scheduler.admin.entity.request.TaskRecordPageRequest;
import com.etl.dataflow.scheduler.admin.entity.vo.DataflowTaskRecordVo;
import com.etl.dataflow.scheduler.admin.mapper.DataflowTaskRecordMapper;
import com.etl.dataflow.scheduler.communication.ExecutorStateChecker;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 任务运行记录 服务实现类
 * </p>
 *
 * @author dx
 * @since 2022-04-24
 */
@Service
public class DataflowTaskRecordService extends ServiceImpl<DataflowTaskRecordMapper, DataflowTaskRecord> implements DefaultService<DataflowTaskRecord> {

    private static final Map<Integer, String> TASK_RECORD_STATE_DICT = MapUtil.<Integer, String>builder()
            .put(TaskStateEnum.RUNNING.getValue(), "运行中")
            .put(TaskStateEnum.TERMINATED.getValue(), "已终止")
            .put(TaskStateEnum.FINISHED.getValue(), "正常结束")
            .put(TaskStateEnum.FATAL_ERROR.getValue(), "致命错误")
            .put(TaskStateEnum.TIMEOUT.getValue(), "执行超时")
            .build();

    private final ExecutorStateChecker executorStateChecker;

    private final DataflowTaskInfoService taskInfoService;

    public DataflowTaskRecordService(ExecutorStateChecker executorStateChecker, DataflowTaskInfoService taskInfoService) {
        this.executorStateChecker = executorStateChecker;
        this.taskInfoService = taskInfoService;
    }

    public R findVoById(String id) {
        DataflowTaskRecord taskRecord = super.getById(id);
        DataflowTaskInfo taskInfo = taskInfoService.getById(taskRecord.getTaskInfoId());
        DataflowTaskRecordVo taskRecordVo = new DataflowTaskRecordVo();
        BeanUtil.copyProperties(taskRecord, taskRecordVo);
        taskRecordVo.setTaskInfo(taskInfo);
        return R.success().put("data", taskRecordVo);
    }

    public R findAllTaskStates() {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TaskStateEnum stateEnum : TaskStateEnum.values()) {
            Map<String, Object> item = new HashMap<>(8);
            item.put("value", stateEnum.getValue());
            item.put("label", stateEnum.getMsg());
            list.add(item);
        }
        return R.success().put("data", list);
    }

    public Page<? extends DataflowTaskRecord> page(TaskRecordPageRequest pageRequest) {
        Page<DataflowTaskRecord> page;
        String keyword = pageRequest.getKeyword();
        String taskState = pageRequest.getTaskState();
        if (StrUtil.isBlank(keyword)) {
            page = super.baseMapper.selectPage(toPage(pageRequest),
                    orLikeAllFieldsWithCustomCondition(pageRequest, DataflowTaskRecord.class, "id", qw -> {
                        if (StrUtil.isNotBlank(taskState)) {
                            qw.eq("task_state", taskState);
                        }
                    })
            );
        } else {
            page = super.baseMapper.paging(toPage(pageRequest), "%" + keyword + "%");
        }
        if (page.getTotal() <= 0 || page.getRecords().isEmpty()) {
            return page;
        }
        List<Long> taskIds = page.getRecords().stream().map(DataflowTaskRecord::getTaskInfoId).collect(Collectors.toList());
        QueryWrapper<DataflowTaskInfo> queryWrapper = new QueryWrapper<>();
        Map<Long, DataflowTaskInfo> taskInfoMap = taskInfoService.list(queryWrapper.in("id", taskIds)).stream().collect(Collectors.toMap(DataflowTaskInfo::getId, v -> v));
        List<DataflowTaskRecordVo> vos = new ArrayList<>();
        for (DataflowTaskRecord record : page.getRecords()) {
            DataflowTaskRecordVo vo = new DataflowTaskRecordVo();
            BeanUtil.copyProperties(record, vo);
            vo.setTaskInfo(taskInfoMap.get(record.getTaskInfoId()));
            this.convertTaskRecordState(vo);
            vos.add(vo);
        }
        Page<DataflowTaskRecordVo> pageVo = new Page<>();
        BeanUtil.copyProperties(page, pageVo);
        pageVo.setRecords(vos);
        return pageVo;
    }

    private void convertTaskRecordState(DataflowTaskRecordVo taskRecord) {
        if (TASK_RECORD_STATE_DICT.containsKey(taskRecord.getTaskState())) {
            String state = TASK_RECORD_STATE_DICT.get(taskRecord.getTaskState());
            taskRecord.setTaskStateName(state);
        }
    }

    public R statistic(String uuid, Long taskId) {
        return this.statisticByHttp(uuid, taskId);
    }

    private R statisticByHttp(String uuid, Long taskId) {
        ExecutorInfo executorInfo = executorStateChecker.getExecutorInfoByUuid(uuid);
        String url = executorInfo.getExecutorUrl() + "/task/statistic?taskId=" + taskId;
        String body;
        try (HttpResponse httpResponse = HttpUtil.createGet(url)
                .execute()) {
            body = httpResponse.body();
        }
        JSONObject json = JSONUtil.parseObj(body);
        R r = new R(Code.SUCCESS);
        r.setCode((Integer) json.get("code"));
        @SuppressWarnings("unchecked")
        Map<String, Object> data = (Map<String, Object>) json.get("data");
        r.setData(data);
        r.setMsg((String) json.get("msg"));
        return r;
    }

}
